#!/usr/bin/env python

# repository builder basing on given paths (divide multiple locations by comma)
# shows an example of using Tilde API

import sys
import os
try: import sqlite3
except ImportError:
    try: from pysqlite2 import dbapi2 as sqlite3
    except ImportError:
        print 'Please, install sqlite3 module!'
        sys.exit()

sys.path.append(os.path.realpath(os.path.dirname(__file__) + '/../')) # path to Tilde root folder

from core.api import API
from core.settings import settings, DATA_DIR

try: workpath = sys.argv[1]
except IndexError: raise RuntimeError('No file / folder defined!')
workpaths = workpath.split(',')

db = sqlite3.connect(os.path.abspath(DATA_DIR + '/tilde.dat'))
db.row_factory = sqlite3.Row
db.text_factory = str

work = API(db_conn = db, filter = settings['filter'])

for target in workpaths:
    if not os.path.exists(os.path.abspath(target)):
        print target + ' is invalid!'
        continue

    tasks = work.savvyize(target, True) # False means non-recursive
    for task in tasks:
        filename = os.path.basename(task)
        
        calc, error = work.parse(task)
        if error:
            print filename, error
            continue
            
        calc, error = work.classify(calc)
        if error:
            print filename, error
            continue
            
        checksum, error = work.save(calc)
        if error:
            print filename, error
            continue
            
        print filename + " added"

print 'Your repository has been built. Run tilde application to browse it.'
